﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entity;
using IRepository;
using IService;
using Microsoft.IdentityModel.Tokens;
namespace Service
{
    public class TypeOfGoodsService : ITypeOfGoodsService
    {
        private readonly ITypeOfGoodsRepository _typeOfGoodsRepository;

        public TypeOfGoodsService(ITypeOfGoodsRepository typeOfGoodsRepository)
        {
            _typeOfGoodsRepository = typeOfGoodsRepository;
        }

        public async Task<List<WMSBasicTypeOfGoods>> GetGoodsTypeTreeAsync(string goodsType = null, string status = null, string @operator = null, DateTime? startTime = null, DateTime? endTime = null)
        {
            var allTypes = await _typeOfGoodsRepository.GetAllGoodsTypesAsync(goodsType, status, @operator, startTime, endTime);
            var rootTypes = allTypes.Where(t => t.parent_category_id == 0).ToList();
            foreach (var root in rootTypes)
            {
                BuildChildren(root, allTypes);
            }
            return rootTypes;
        }

        private void BuildChildren(WMSBasicTypeOfGoods parent, List<WMSBasicTypeOfGoods> allTypes)
        {
            var children = allTypes.Where(t => t.parent_category_id == parent.product_type_id).ToList();
            if (children.Any())
            {
                parent.Children.AddRange(children);
                foreach (var child in children)
                {
                    BuildChildren(child, allTypes);
                }
            }
        }

        /// <summary>
        /// 添加查询上级分类
        /// </summary>
        /// <returns></returns>
        public async Task<List<WMSBasicTypeOfGoods>> GetParentTypeOptionsAsync()
        {
            // 调用Repository查询所有有效类型（is_delete = '0'）
            var allTypes = await _typeOfGoodsRepository.GetSelectTypesAsync();

            // 构建树形结构（用于前端显示层级，如"一级分类 > 二级分类"）
            var rootTypes = allTypes.Where(t => t.parent_category_id == 0).ToList();
            foreach (var root in rootTypes)
            {
                BuildChildren(root, allTypes);
            }

            // 扁平化为下拉选项（带层级前缀，如"-- 二级分类"）
            var options = new List<WMSBasicTypeOfGoods>();
            FlattenForOptions(rootTypes, options, 0);

            return options;
        }

        // 为下拉选项（添加层级前缀）
        private void FlattenForOptions(
            List<WMSBasicTypeOfGoods> nodes,
            List<WMSBasicTypeOfGoods> options,
            int level)
        {
            foreach (var node in nodes)
            {
                // 复制节点并添加层级前缀（如"-- "表示二级，"---- "表示三级）
                var option = new WMSBasicTypeOfGoods
                {
                    product_type_id = node.product_type_id,
                    product_type_name = level == 0 ? node.product_type_name : $"{new string('-', level * 2)} {node.product_type_name}",
                    product_type_code = node.product_type_code
                };
                options.Add(option);

                // 递归处理子节点（层级+1）
                if (node.Children.Any())
                {
                    FlattenForOptions(node.Children, options, level + 1);
                }
            }
        }

        public async Task AddTypesAsync(AddWMSBasicTypeOfGoods model)
        {
            if (string.IsNullOrWhiteSpace(model.product_type_name))
            {
                throw new ArgumentException("货品信息不能为空");
            }
            await _typeOfGoodsRepository.AddTypesAsync(model);
        }

        public async Task<AddWMSBasicTypeOfGoods> SelectTypeAsync(string product_type_code)
        {
            if (string.IsNullOrWhiteSpace(product_type_code))
            {
                throw new ArgumentException("货品信息编号为空");
            }
            return await _typeOfGoodsRepository.SelectTypeAsync(product_type_code);
        }

        public async Task DeleteTypesAsync(string product_type_code)
        {
            if (string.IsNullOrWhiteSpace(product_type_code))
            {
                throw new ArgumentException("货品信息编号为空");
            }
            await _typeOfGoodsRepository.DeleteTypesAsync(product_type_code);
        }

        public async Task UpdateTypesAsync(AddWMSBasicTypeOfGoods model)
        {
            if (string.IsNullOrWhiteSpace(model.product_type_name))
            {
                throw new ArgumentException("货品信息不能为空");
            }
            await _typeOfGoodsRepository.UpdateTypesAsync(model);
        }
        /// <summary>
        /// 根据类型ID获取类型名称
        /// </summary>
        public async Task<string> GetTypeNameByIdAsync(int typeId)
        {
            // 业务参数校验
            if (typeId <= 0)
                throw new ArgumentException("货品类型ID必须大于0");

            try
            {
                return await _typeOfGoodsRepository.GetTypeNameByIdAsync(typeId);
            }
            catch (Exception ex)
            {
                throw new Exception($"获取类型ID={typeId}的名称失败：" + ex.Message);
            }
        }
        /// <summary>
        /// 将扁平列表转换为树形结构（递归处理父子关系）
        /// </summary>
        private List<WMSBasicTypeOfGoods> BuildTypeTree(List<WMSBasicTypeOfGoods> flatTypes)
        {
            // 1. 找出所有顶级节点（parent_category_id = 0，即没有父节点）
            var rootTypes = flatTypes.Where(t => t.parent_category_id == 0).ToList();

            // 2. 为每个顶级节点递归添加子节点
            foreach (var root in rootTypes)
            {
                AddChildrenToParent(root, flatTypes);
            }

            return rootTypes;
        }

        /// <summary>
        /// 递归为父节点添加子节点
        /// </summary>
        private void AddChildrenToParent(WMSBasicTypeOfGoods parent, List<WMSBasicTypeOfGoods> allTypes)
        {
            // 找出当前父节点的子节点（parent_category_id = 父节点的product_type_id）
            var children = allTypes
                .Where(t => t.parent_category_id == parent.product_type_id)
                .OrderBy(t => t.sorting) // 按排序字段排序
                .ToList();

            if (children.Any())
            {
                parent.Children = children;
                // 递归为子节点添加它们的子节点
                foreach (var child in children)
                {
                    AddChildrenToParent(child, allTypes);
                }
            }
        }

        public Task<List<WMSBasicTypeOfGoods>> GetGoodsTypeTreeAsync()
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 批量根据类型ID获取类型名称（新增实现）
        /// </summary>
        public async Task<Dictionary<int, string>> GetTypeNamesByIdsAsync(List<int> typeIds)
        {
            if (typeIds == null || typeIds.Count == 0)
                return new Dictionary<int, string>();

            try
            {
                return await _typeOfGoodsRepository.GetTypeNamesByIdsAsync(typeIds);
            }
            catch (Exception ex)
            {
                throw new Exception($"批量获取类型名称失败：{ex.Message}", ex);
            }
        }
    }
}
